import logging
from config.common import DM_HOST, DM_PORT, DM_USER, DM_PASSWORD, DM_DATABASE
import dmPython
from dbutils.pooled_db import PooledDB


class DmClient(object):
    def __init__(self):
        host = DM_HOST
        port = DM_PORT
        user = DM_USER
        password = DM_PASSWORD
        database = DM_DATABASE
        dbconfig = {
            "server": host,
            "user": user,
            "port": port,
            "password": password,
        }
        self.cnxpool = PooledDB(
            creator=dmPython,  # 使用dmPython作为数据库模块
            mincached=10,  # 初始化时，链接池中至少创建的链接数
            maxcached=20,  # 链接池中最多闲置的链接数
            maxconnections=100,  # 链接池允许的最大链接数
            blocking=True,  # 连接池中如果没有可用连接后，是否阻塞等待
            **dbconfig,  # 其他数据库连接参数
        )
        logging.info("[SUCCESS] 数据库{}连接成功".format(database))

    def execute_query(self, query, params=None, commit=False, fetch=False):
        conn = self.cnxpool.connection()
        cursor = conn.cursor()
        try:
            cursor.execute(query, params)
            if commit:
                conn.commit()
            if fetch:
                result = cursor.fetchall()
            else:
                result = None
            return result
        finally:
            cursor.close()
            conn.close()

    def execute_query_by_id(self, query, params=None):
        conn = self.cnxpool.connection()
        cursor = conn.cursor()
        try:
            cursor.execute(query, params)
            result = cursor.fetchone()
            return result
        finally:
            cursor.close()
            conn.close()


if __name__ == "__main__":
    dmClient = DmClient()
    results = dmClient.execute_query(f"select * from {DM_DATABASE}.T_FEATURE_METRICS where ID = 1", fetch=True)
    if results and len(results) > 0:
        for row in results:
            print(row)
